export default {

    /**
     * 二进制转JSON
     * @param {ArrayBuffer} buffer 二进制
     */
    arrayBufferToJson(arr) {
        let str = this.arrayBufferToString(arr);
        return JSON.parse(str);
    },

    /**
     * 二进制转字符串
     * @param {ArrayBuffer} buffer 二进制
     */
    arrayBufferToString(arr) {
        if (typeof arr === 'string') {
            return arr;
        }
        var dataview = new DataView(arr);
        var ints = new Uint8Array(arr.byteLength);
        for (var i = 0; i < ints.length; i++) {
            ints[i] = dataview.getUint8(i);
        }
        arr = ints;
        var str = '',
            _arr = arr;
        // eslint-disable-next-line no-redeclare
        for (var i = 0; i < _arr.length; i++) {
            var one = _arr[i].toString(2),
                v = one.match(/^1+?(?=0)/);
            if (v && one.length == 8) {
                var bytesLength = v[0].length;
                var store = _arr[i].toString(2).slice(7 - bytesLength);
                for (var st = 1; st < bytesLength; st++) {
                    store += _arr[st + i].toString(2).slice(2);
                }
                str += String.fromCharCode(parseInt(store, 2));
                i += bytesLength - 1;
            } else {
                str += String.fromCharCode(_arr[i]);
            }
        }
        return str;
    },

    /**
     * json 转ArrayBuffer
     * @param {Object} json json数据
     */
    jsonToArrayBuffer(json) {
        return this.stringToArrayBuffer(JSON.stringify(json));
    },

    /**
     * 字符串转ArrayBuffer
     * @param {Object} str 字符串
     */
    stringToArrayBuffer(str) {
        var bytes = new Array();
        var len, c;
        len = str.length;
        for (var i = 0; i < len; i++) {
            c = str.charCodeAt(i);
            if (c >= 0x010000 && c <= 0x10FFFF) {
                bytes.push(((c >> 18) & 0x07) | 0xF0);
                bytes.push(((c >> 12) & 0x3F) | 0x80);
                bytes.push(((c >> 6) & 0x3F) | 0x80);
                bytes.push((c & 0x3F) | 0x80);
            } else if (c >= 0x000800 && c <= 0x00FFFF) {
                bytes.push(((c >> 12) & 0x0F) | 0xE0);
                bytes.push(((c >> 6) & 0x3F) | 0x80);
                bytes.push((c & 0x3F) | 0x80);
            } else if (c >= 0x000080 && c <= 0x0007FF) {
                bytes.push(((c >> 6) & 0x1F) | 0xC0);
                bytes.push((c & 0x3F) | 0x80);
            } else {
                bytes.push(c & 0xFF);
            }
        }
        var array = new Int8Array(bytes.length);
        // eslint-disable-next-line no-redeclare
        for (var i = 0; i <= bytes.length; i++) {
            array[i] = bytes[i];
        }
        return array.buffer;
    }
}